<template>
  <div id="app">
    <div class="app-top">
      <div>加载<input type="number" v-model="totalPage">页</div>
      <button @click="openPdfMarking">确定</button>
    </div>
    <marking
      class="marking"
      :data-load-fn="dataLoadFn"
      :textpopup-disableelement="['highlight']"
      hide-contextmenupopup
      hide-pagenav
      :contextmenupopup-disableelement="['highlight','pan','freeLine','freeText']"
      @annotation-change="handleAnnotationChange"
      ref="marking">
      <template #watermark="{pageIndex}">
        <div style="font-size: 100px;color: red;transform: rotate(45deg)">水印{{pageIndex}}</div>
      </template>
    </marking>
    <div class="selection-toolbar" ref="selectionToolbar" @touchstart.stop @mousedown.stop>
      <div class="selection-toolbar-item" @click="handleSelectionToolbarItemClick(item)"
           v-for="(item,index) in toolbarList" :key="index">{{item.label}}
      </div>
    </div>
    <div class="selection-contextmenu" ref="selectionContextmenu" @touchstart.stop @mousedown.stop>
      <div class="selection-contextmenu-item" @click="handleSelectionContextmenuItemClick(item)"
           v-for="(item,index) in contextmenuList" :key="index">{{item.label}}
      </div>
    </div>
  </div>
</template>

<script>
  // import Marking from './components/Marking/src/Component'
  import Marking, {SCRAWLTYPE} from './components/Marking'
  import {addEventListener} from "@/util/eventManager";
  // import Marking from '..'

  // console.log(require('..'))

  // console.log(SCRAWLTYPE)

  // let dirName = 'test'

  import picData from './testData/picData.json'

  const textData = {
    '0.json': require('./testData/0.json'),
    '1.json': require('./testData/1.json'),
    '2.json': require('./testData/2.json'),
    '3.json': require('./testData/3.json'),
  }

  const fileCount = 4
  let totalPage = 10

  let dirName = 'data'

  // let ip = '192.168.137.193'
  export default {
    name: 'app',
    components: {Marking},
    data() {
      return {
        totalPage: totalPage,
        toolbarList: [],
        contextmenuList: [],
      }
    },
    computed: {
      marking() {
        return this.$refs.marking
      },
      selectionToolbar() {
        return this.$refs.selectionToolbar
      },
      selectionContextmenu() {
        return this.$refs.selectionContextmenu
      },
    },
    async mounted() {
      this.openPdfMarking()
      // this.marking.setPointerType('hand')
      // this.marking.showMark()
      // this.marking.addAnnotationData({
      //   start: '0-0',
      //   end: '0-20',
      // })
      // this.marking.addAnnotationData({
      //   start: '0-25',
      //   end: '0-55',
      //   className: 'underline'
      // })
      //
      // this.marking.addAnnotationData({
      //   pageIndex: 0,
      //   className: 'line',
      //   attrs: {
      //     points: [100, 100, 200, 100, 200, 200, 100, 200],
      //     stroke: 'red'
      //   }
      // })
      //
      // this.marking.addAnnotationData({
      //   pageIndex: 0,
      //   attrs: {
      //     height: 500,
      //     width: 500,
      //     x: 300,
      //     y: 200
      //   }
      // })
      //
      // this.marking.addAnnotationData({
      //   pageIndex: 0,
      //   className: 'arrow',
      //   attrs: {
      //     points: [100, 100, 200, 100],
      //     stroke: 'red'
      //   }
      // })
      //
      // this.marking.addAnnotationData({
      //   start: '0-56',
      //   end: '0-60',
      //   className: 'underline',
      //   attrs: {
      //     strokeWidth: 5,
      //     stroke: 'red',
      //   }
      // }, 'fatiao')

      // let res = await fetch('http://127.0.0.1:8360/index/getWj?id=25D7C5C4295F4AF292551B62DF6EBD97')
      // console.log(await res.json())
    },
    methods: {
      async openPdfMarking() {
        // let res = await fetch(`http://${ip}:8360/index/getIdList?limit=${this.totalPage}`)
        // let data = await res.json()

        let data = []
        for (let i = 0; i < this.totalPage; i++) {
          let m = i % fileCount
          // let res = await fetch(`static/${dirName}/${m}.json`)
          // let text = await res.json()
          data.push({
            pageId: m,
            // imgSrc: `static/${dirName}/${m}.jpg`,
            // words: text.words
          })
        }
        let annotationList = JSON.parse(localStorage.getItem('annotationList'))
        // annotationList = Object.keys(annotationList).map(annotationId => annotationList[annotationId])

        let annotations = []
        for (const annotationListKey in annotationList) {
          annotations = annotations.concat(annotationList[annotationListKey])
        }

        await this.marking.open({data, annotationList: annotations})

        this.marking.addAnnotationData({
          start: '0-25',
          end: '0-55',
          className: 'underline',
          attrs: {
            stroke: 'red',
            strokeWidth: 10
          }
        })
      },
      async dataLoadFn(arg) {

        // let res = await fetch(`http://${ip}:8360/index/getWj?id=${arg.id}`)
        // let wj = await res.json()
        // // console.log(wj)
        // return {
        //   imgSrc: wj.img,
        //   words: wj.words
        // }

        // console.log(arg)
        if (arg.pageIndex === 10) return {imgSrc: null, words: null}
        let m = arg.pageId
        let text = textData[`${m}.json`]
        let pic = picData[`${m}.jpg`]
        return {
          imgSrc: pic,
          words: JSON.parse(JSON.stringify(text.words))
        }
      },
      handleAnnotationChange(annotations, action) {
        // console.log(annotations)
        let annotationList = JSON.parse(localStorage.getItem('annotationList')) || {}
        if (action === 'add') {
          for (const annotationId in annotations) {
            annotationList[annotationId] = annotations[annotationId]
          }
          localStorage.setItem('annotationList', JSON.stringify(annotationList))
        } else if (action === 'delete') {
          for (const annotationId in annotations) {
            delete annotationList[annotationId]
          }
          localStorage.setItem('annotationList', JSON.stringify(annotationList))
        }
        // console.log('handleAnnotationChange', action, annotations)
      },
      clipComplete(clipData) {
        console.log('clipComplete', clipData)
      },
      handleMarkMouseenter(mark, evt) {
        console.log('handleMarkMouseenter', mark, evt)
      },
      handleMarkClick(mark, evt) {
        console.log('handleMarkClick', mark, evt)
      },
      scrawlComplete(scrawlData) {
        let scrawlList = JSON.parse(localStorage.getItem('scrawlList')) || []
        let index = scrawlList.findIndex(scrawlItem => scrawlItem.pageIndex === scrawlData.pageIndex)
        if (index > -1) scrawlList.splice(index, 1)
        scrawlList.push(scrawlData)
        localStorage.setItem('scrawlList', JSON.stringify(scrawlList))
      },
      selectionChange(selection, ev) {
        if (!selection) return
        this.toolbarList = [
          {
            label: '复制文本',
            onclick: () => this.marking.copySelectText()
          },
          {
            label: '标注',
            onclick: () => {
              let markList = JSON.parse(localStorage.getItem('markList')) || []
              markList.push({
                start: selection.start,
                end: selection.end
              })
              localStorage.setItem('markList', JSON.stringify(markList))

              this.marking.addMark({
                start: selection.start,
                end: selection.end
              })
            }
          },
          {
            label: 'alert文本',
            onclick: () => window.alert(selection.text)
          }
        ]
        this.showSelectionToolbar(ev)
      },
      showSelectionToolbar(ev = event) {
        let pos = {x: 0, y: 0}
        // console.log(ev)
        if (ev.changedPointers) {
          pos.x = ev.changedPointers[0].pageX
          pos.y = ev.changedPointers[0].pageY
        } else if (ev.changedTouches) {
          pos.x = ev.changedTouches[0].pageX
          pos.y = ev.changedTouches[0].pageY
        } else {
          pos.x = ev.pageX
          pos.y = ev.pageY
        }
        this.selectionToolbar.style.top = `${pos.y - this.selectionToolbar.offsetHeight - 30}px`
        this.selectionToolbar.style.left = `${pos.x - 30}px`
        this.selectionToolbar.style.visibility = 'visible'
        addEventListener("mousedown", this.hideSelectionToolbar)
        window.addEventListener("wheel", this.hideSelectionToolbar, true)
      },
      hideSelectionToolbar() {
        this.selectionToolbar.style.visibility = 'hidden'
        removeEventListener("mousedown", this.hideSelectionToolbar)
        window.removeEventListener("wheel", this.hideSelectionToolbar, true)
      },
      handleSelectionToolbarItemClick(item) {
        if (item.onclick) item.onclick()
        this.hideSelectionToolbar()
      },
      contextmenu(selection) {
        if (selection) {
          this.contextmenuList = [
            {
              label: '复制文本',
              onclick: () => this.marking.copySelectText()
            },
            {
              label: 'alert文本',
              onclick: () => window.alert(selection.text)
            }
          ]
        } else {
          this.contextmenuList = [
            {
              label: '这个是没有选中文本时的右键菜单',
              onclick: () => window.alert('这个是没有选中文本时的右键菜单的点击事件')
            },
            {
              label: '顺时针旋转90°',
              onclick: () => this.marking.rotateCw()
            },
            {
              label: '逆时针旋转90°',
              onclick: () => this.marking.rotateCcw()
            },
            {
              label: '调整至实际大小',
              onclick: () => this.marking.setScaleType('page-actual')
            },
            {
              label: '调整至适合页面',
              onclick: () => this.marking.setScaleType('page-fit')
            },
            {
              label: '调整至适合页宽',
              onclick: () => this.marking.setScaleType('page-width')
            }
          ]
        }
        this.showSelectionContextmenu()
      },
      showSelectionContextmenu() {
        this.selectionContextmenu.style.top = `${event.pageY - 10}px`
        this.selectionContextmenu.style.left = `${event.pageX + 10}px`
        this.selectionContextmenu.style.visibility = 'visible'
        addEventListener("mousedown", this.hideSelectionContextmenu)
        window.addEventListener("wheel", this.hideSelectionContextmenu, true)
      },
      hideSelectionContextmenu() {
        this.selectionContextmenu.style.visibility = 'hidden'
        removeEventListener("mousedown", this.hideSelectionContextmenu)
        window.removeEventListener("wheel", this.hideSelectionContextmenu, true)
      },
      handleSelectionContextmenuItemClick(item) {
        if (item.onclick) item.onclick()
        this.hideSelectionContextmenu()
      },
      progressChange(a) {
        // console.log(a)
      },
      pageChange(a) {
        // console.log(a)
      },
      handlePageUnload(e) {
        console.log(e)
      },
      handleRectDrawComplete(e) {
        e.map(item => {
          this.marking.addMark(item)
        })
      }
    }
  }
</script>

<style lang="scss">
  :root {
    --primary-color: #fff;
    --secondary-color: #f5f5f5;
    --border-color: #e0e0e0;
    --button-hover-color: #f6f6f6;
    --button-active-color: #f0f0f0;
    --text-color: #333;
    --icon-color: #757575;
    --icon-active-color: #757575;
    --left-panel-width: 300px;
  }

  html, body {
    margin: 0;
    padding: 0;
    overflow: hidden;
  }
</style>
<style lang="scss" scoped>
  #app {
    width: 100vw;
    height: 100vh;
    cursor: default;
    display: flex;
    flex-direction: column;

    .app-top {
      height: 40px;
      background-color: blanchedalmond;
      flex-shrink: 0;
      display: flex;
      align-items: center;
    }

    .marking {
      flex: 1;
      height: calc(100% - 40px);
    }

    .marking-tool-item {
      font-size: 14px;
      /*display: inline-block;*/
      box-sizing: border-box;
      max-height: calc(100% - 10px);
      border-radius: 5px;
      margin-top: 5px;
      margin-left: 5px;
      vertical-align: middle;

      &.active {
        background-color: #cccccc;
        color: #fff;
      }

      img {
        box-sizing: border-box;
        padding: 2px;
        height: 20px;
      }

      &:hover {
        background-color: #cccccc;
        color: #fff;
      }

      select {
        height: 100%;
        width: 100%;
        border: none;
        outline: none;
        background-color: transparent;
        appearance: none;
        background-position: right center;
        background-repeat: no-repeat;
        background-size: 20px;
        background-image: url("./assets/img/arrow_right.png");
        padding-right: 20px;
        padding-left: 10px;

        /*option {*/
        /*  background-color: red;*/
        /*}*/
      }
    }

    .markline {
      width: 200px;
      background-color: #409EFF;
    }

    .selection-toolbar {
      position: absolute;
      top: 0;
      left: 0;
      background-color: white;
      border-radius: 3px;
      border: 1px solid #ccc;
      visibility: hidden;

      .selection-toolbar-item {
        display: inline-block;
        padding: 0 5px;
        line-height: 30px;
        border-right: 1px solid #ccc;

        &:nth-last-child(1) {
          border-right: none;
        }

        &:hover {
          background-color: #cccccc;
        }
      }

    }

    .selection-contextmenu {
      position: absolute;
      top: 0;
      left: 0;
      background-color: white;
      border-radius: 3px;
      border: 1px solid #ccc;
      visibility: hidden;

      .selection-contextmenu-item {
        text-indent: 20px;
        line-height: 30px;
        padding-right: 10px;
        border-bottom: 1px solid #ccc;

        &:nth-last-child(1) {
          border-bottom: none;
        }

        &:hover {
          background-color: #ccc;
        }
      }
    }
  }
</style>
